package com.py.framework.scheduler.job.factory;

import com.py.framework.core.common.SpringContextHolder;
import com.py.framework.core.exception.ServiceException;
import com.py.framework.core.log.ExceptionLogger;
import com.py.framework.scheduler.job.Job;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 任务执行抽象类
 *
 * @author Leegern
 * @date 2018年5月7日
 */
public abstract class AbstractJobFactory {

    private static Logger logger = Logger.getLogger(ExceptionLogger.class);

    /**
     * 执行方法
     *
     * @param job
     */
    public void invoke(Job job) {
        if (StringUtils.isNotBlank(job.getJobClassName())) {
            try {
                Class<?> clazz = Class.forName(job.getJobClassName());
                // 从spring容器获取bean,否则无法注入
                Object obj = SpringContextHolder.getBean(clazz);
                // 反射方法
                Method method = null;
                if (null != obj) {
                    method = obj.getClass().getDeclaredMethod(job.getJobMethodName(), Job.class);
                } else {
                    obj = clazz.newInstance();
                    if (null != obj) {
                        method = obj.getClass().getDeclaredMethod(job.getJobMethodName(), Job.class);
                    }
                }
                if (null == method) {
                    throw new ServiceException("JobDetail's doJob method not found, please check the config!");
                }
                method.invoke(obj, job);
            } catch (ClassNotFoundException e) {
                logger.error(job.getJobName() + "发生异常，错误原因" + e.getMessage());
                ExceptionLogger.error(e);
            } catch (NoSuchMethodException e) {
                logger.error(job.getJobName() + "发生异常，错误原因" + e.getMessage());
                ExceptionLogger.error(e);
            } catch (IllegalAccessException e) {
                logger.error(job.getJobName() + "发生异常，错误原因" + e.getMessage());
                ExceptionLogger.error(e);
            } catch (InvocationTargetException e) {
                logger.error(job.getJobName() + "发生异常，错误原因" + e.getMessage());
                ExceptionLogger.error(e);
            } catch (InstantiationException e) {
                logger.error(job.getJobName() + "发生异常，错误原因" + e.getMessage());
                ExceptionLogger.error(e);
            }
        }
    }
}